package com.zhugang.week05;

/**
 * @program algorithms
 * @description: findMin
 * @author: chanzhugang
 * @create: 2022/07/06 11:15
 */
public class FindMin {

    public static void main(String[] args) {
        FindMin findMin = new FindMin();
        int[] nums = new int[]{3, 4, 5, 1, 2};
        int index = findMin.findMin(nums);
        System.out.println(index);
    }

    /**
     * 153 寻找旋转排序数组中的最小值
     *
     * @param nums
     * @return
     */
    public int findMin(int[] nums) {
        // 3,4,5, 1,2
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (low == high) {
                return nums[mid];
            }

            if ((mid != 0 && nums[mid] < nums[mid - 1]) || (mid == 0 && nums[mid] < nums[high])) {
                // mid 比前面一个小 、 整个有序
                return nums[mid];
            } else if (nums[mid] > nums[high]) {
                // 右侧循环有序
                low = mid + 1;
            } else {
                // 左侧循环有序
                high = mid - 1;
            }
        }
        return -1;
    }
}